# encoding: utf-8

import requests,json,time

import smtplib
from email.mime.text import MIMEText
from email.header import Header

LOGIN_URL='https://www.fengyunbowei.com/soil/login?username=aiweite&password=123456'
DATA_URL='https://www.fengyunbowei.com/soil/css/latest?id={0}'

#服务器域名
# METEO_SERVER='http://meteo.awit.net.cn:10280/GuiYang_weather_BS/'
METEO_SERVER='http://localhost:8080/GuiYang_weather_BS/'
#获取所有路线
METEO_ROADS=METEO_SERVER+'weatherData.do?getActivedRoad'
#获取路线的气象站
METEO_STATIONS=METEO_SERVER+'weatherData.do?getActivedStation&rid={0}'
#上传数据
METEO_PUSH=METEO_SERVER+'push.do?pushCheckData&username=admin&password=123456'

# 第三方 SMTP 服务
mail_host = "smtp.qq.com"  # 设置服务器
mail_user = "910325476@qq.com"  # 用户名
mail_pass = "jirfmwwwjfgybfhj"  # 口令

sender = '910325476@qq.com'
receivers = ['kuan.zhou@awit.net.cn']  # 接收邮件，可设置为你的QQ邮箱或者其他邮>箱
#警告信息

warnMsgArr=[]
def warn(msg):
    print(msg)
    warnMsgArr.append(msg)

def sendMail():
    if len(warnMsgArr)>0:
        msg=''
        for line in warnMsgArr:
            msg += line + '\n'
        message = MIMEText(msg, 'plain', 'utf-8')
        message['From'] = Header("Meteo数据服务器", 'utf-8')
        message['To'] = Header("提醒", 'utf-8')
        subject = '服务器校准数据异常'
        message['Subject'] = Header(subject, 'utf-8')
        try:
            smtpObj = smtplib.SMTP_SSL(mail_host, 465)
            smtpObj.set_debuglevel(1)
            smtpObj.login(mail_user, mail_pass)
            smtpObj.sendmail(sender, receivers, message.as_string())
            print "邮件发送成功"
        except smtplib.SMTPException:
            print "Error: 无法发送邮件"


#获取国家站
def loadStationByRoad(roadId,roadCode):
    req = requests.get(METEO_STATIONS.format(roadId))
    stationList=[]
    for station in req.json()['obj']['data']:
        if str(station['stationCode']).startswith(roadCode+'-'):
            stationList.append({
                'roadCode':roadCode,
                'stationId':str(station['stationCode']).replace(roadCode+'-','')
            })
    return stationList

#获取所有路线
def loadAllRoad():
    req = requests.get(METEO_ROADS)
    if req.status_code==200:
        return req.json()['obj']['data']
    else:
        warn('下载路线异常：'+req.text)
        return None


#自动站接口-最新的一笔数据
def login():
    session = requests.session()
    req = session.post(LOGIN_URL.format('login'))
    if req.status_code==200:
        return session
    else:
        warn('登录异常：'+req.text)
        return None

def CheckDataBody(
        roadCode,stationId,type,time,rhumOut,tempOut,wind,windDirc,rainDay,barometer
):
    if rhumOut is None:rhumOut=0.0
    if tempOut is None: tempOut = 0.0
    if wind is None: wind = 0.0
    if windDirc is None: windDirc = 0.0
    if rainDay is None: rainDay = 0.0
    if barometer is None: barometer= 0.0
    return {
        'roadCode':roadCode,'stationType':type,'rhumIn':0.00,'rhumOut':rhumOut,'time':time,
        'tempIn':0.00,'tempOut':tempOut,'solarRadia':0.00,'uv':0.00,
        'ice0Temp':0.00,'ice0Alarm':'010','ice0Thick':0.00,
        'ice1Temp':0.00,'ice1Alarm':'000','ice1Thick':0.00,
        'barometer':barometer,'wind':wind,'windDirc':windDirc,'winAve':0.00,
        'rainRate':0.00,'rainDay':rainDay,'rainMonth':0.00,'rainYear':0.00,
        'conBattery':0.00,'tempExtra':',,,,,,','soilTemp':',,,','leafTemp':',,,',
        'rhumExtra':',,,,,,','soilMoinst':',,,','leafWet':',,,0','stationId':stationId
    }

#下载国家站数据
def downStationData(stationList,session,roadCode):
    s=time.time()
    data=[]
    for station in stationList:
        stationId = station['stationId']
        req = session.get(DATA_URL.format(stationId))
        if req.status_code != 200:
            warn('[{0}_{1}]接收数据异常：'.format(roadCode,stationId))
        else:
            data.append(req.json())
    print('[{0}]获取耗时:'.format(roadCode) + str((time.time() - s) * 1000) + 'ms')
    return data

#修复数据
def fixData(data):
    result={}
    for roadCode in data:
        result[roadCode]=[]
        for d in data[roadCode]:
            res = {
                'u': float(d['rhu']) if d['rhu'] else 0,
                'temp': float(d['tem']) if d['tem'] else 0,
                'wd10df': float(d['win_s_avg_10mi']) if d['win_s_avg_10mi'] else 0,
                'wd10dd': float(d['win_d_avg_10mi']) if d['win_d_avg_10mi'] else 0,
                'hourr': float(d['pre_24h']) if d['pre_24h'] else 0,
                'datetime': data[roadCode][0]['datetime'],
                'prs':float(d['prs']) if d['prs'] else 0
            }
            result[roadCode].append(
                CheckDataBody(roadCode, d['stationId'], 2, res['datetime'], res['u'],
                              res['temp'],
                              res['wd10df'], res['wd10dd'] ,
                              res['hourr'],
                              res['prs']
                              )
                                    )
    return result

#上传数据到服务器
def pushCheckData(checkDataArr):
    print(checkDataArr)
    try:
        req=requests.post(METEO_PUSH,data=json.dumps(checkDataArr),headers  = {'Content-Type': 'application/json;charset=UTF-8'})
        print(req.json())
        if req.status_code != 200:
            warn('上传数据失败:【{0}】'.format(checkDataArr))
    except Exception:
        warn('meteo服务器无法使用:【{0}】'.format(checkDataArr))

'''
每小时的20分执行一次，将数据存放到时间表中
'''
if __name__=='__main__':
    session = login()
    if session is None:
        warn('登录失败：无法获取session')
    allRoads = loadAllRoad()
    if allRoads is not None:
        allData={}
        for road in allRoads:
            roadCode=road['roadCode']
            stationList=loadStationByRoad(road['id'],roadCode)
            data = downStationData(stationList, session,roadCode)
            if len(data)!=0:
                allData[roadCode]=data
        fix_data = fixData(allData)
        pushCheckData(fix_data)
        # sendMail()

'''
{
    "pre": null,	#降雨
    "tem": 11.7,    #气温
    "datetime": "2020-02-25 11:00:00",
    "vis": 3100,    #能见度
    "win_s_max": 0.8,   #最大风速
    "clo_cov": null,
    "prs": 979.8,   #气压
    "win_d_inst": 34,   #瞬时风向
    "pre_12h": 0,   #12h降雨
    "pre_6h": 0,    #6h降雨
    "win_d_avg_10mi": 14,   #10分钟平均风向
    "win_d_s_max": 14,      #最大风向
    "win_s_inst": 1.5,      #瞬时间风速
    "wep_now": 10,
    "pre_24h": 0,   #24h降雨
    "win_s_avg_10mi": 0.8,  #10分钟平均风速
    "win_s_avg_2mi": 1.1,   #2分钟平均风速
    "rhu": 90,      #湿度
    "stationId": "57514",
    "tem_min_24h": 9.8,     #24h最低气温
    "vis_min": 2689,    #最小能见度
    "win_d_avg_2mi": 28,    #2分钟平均风向
    "tem_max_24h": 13.3,    #24h最高气温
    "pre_1h": 0,    #1h降雨
    "pre_3h": 0     #3h降雨
}
'''